﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.LandlordTrainingForRetainersIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Extensions;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Roster;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class LandlordTrainingForRetainersIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency LandlordTrainingForRetainersIssueFrequency = IssueBase.IssueFrequency.VeryCommon;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    private bool ConditionsHold(Hero issueGiver)
    {
      ItemObject primaryProduction = issueGiver.CurrentSettlement?.Village?.VillageType?.PrimaryProduction;
      if (!issueGiver.IsRuralNotable || !issueGiver.CurrentSettlement.IsVillage || !primaryProduction.HasHorseComponent)
        return false;
      return primaryProduction.ItemCategory == DefaultItemCategories.Horse || primaryProduction.ItemCategory == DefaultItemCategories.NobleHorse || primaryProduction.ItemCategory == DefaultItemCategories.WarHorse;
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnSelected), typeof (LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssue), IssueBase.IssueFrequency.VeryCommon));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssue), IssueBase.IssueFrequency.VeryCommon));
    }

    private IssueBase OnSelected(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssue(issueOwner);
    }

    public class LandlordTrainingForRetainersIssue : IssueBase
    {
      private const int QuestTimeLimit = 60;
      private const int IssueDuration = 30;
      private const int AlternativeSolutionTroopTierRequirement = 2;
      private const int SkillLimit = 120;

      internal static void AutoGeneratedStaticCollectObjectsLandlordTrainingForRetainersIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      public override IssueBase.AlternativeSolutionScaleFlag AlternativeSolutionScaleFlags
      {
        get
        {
          return IssueBase.AlternativeSolutionScaleFlag.Casualties | IssueBase.AlternativeSolutionScaleFlag.FailureRisk;
        }
      }

      private int BorrowedTroopCount => 3 + MathF.Ceiling(17f * this.IssueDifficultyMultiplier);

      protected override bool IssueQuestCanBeDuplicated => false;

      public override int AlternativeSolutionBaseNeededMenCount
      {
        get => 8 + MathF.Ceiling(19f * this.IssueDifficultyMultiplier);
      }

      protected override int AlternativeSolutionBaseDurationInDaysInternal
      {
        get => 9 + MathF.Ceiling(10f * this.IssueDifficultyMultiplier);
      }

      protected override int RewardGold
      {
        get => (int) (2000.0 + 4000.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override TextObject Title
      {
        get
        {
          TextObject parent = new TextObject("{=q2aed7tv}Train troops for {ISSUE_OWNER.NAME}");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=va7rEVZn}{ISSUE_OWNER.NAME}, a landowner in {ISSUE_SETTLEMENT}, needs some of his watchmen and retainers to gain some real war experience. {?ISSUE_OWNER.GENDER}She{?}He{\\?} wants you to take them with you on some fairly safe expeditions, such as hunting some bandits. ");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          parent.SetTextVariable("ISSUE_SETTLEMENT", this.IssueSettlement.Name);
          return parent;
        }
      }

      protected override int CompanionSkillRewardXP
      {
        get => (int) (500.0 + 700.0 * (double) this.IssueDifficultyMultiplier);
      }

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          return new TextObject("{=dBphGKTI}Things are getting a bit rough around these parts. I have some lads who help me out with local troublemakers, but they wouldn't last long against real warriors. Maybe you could take them out, show them what actual war is about. I'm not expecting you to make them fit for a noble's retinue, but at least I want to give the bandits around here some pause for thought.[if:convo_bored][ib:closed]");
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=1REltXXz}I'll help if I can.");
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          return new TextObject("{=uLiRasv1}Maybe you could take them in your party for a while, until they get a bit of experience?[if:convo_thinking]");
        }
      }

      public override TextObject IssueAlternativeSolutionExplanationByIssueGiver
      {
        get
        {
          return new TextObject("{=rutgr1VF}Or if you can assign a companion for a while, they can stay here and train the men... I will also give you some provisions and money for their expenses and your trouble.[if:convo_thinking]");
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          return new TextObject("{=QxEPwLyp}I'll take your men into my party and show them a bit of the world.");
        }
      }

      public override TextObject IssueAlternativeSolutionAcceptByPlayer
      {
        get => new TextObject("{=oT4JNyFp}I will assign one of my companions to train your men.");
      }

      public override TextObject IssueAlternativeSolutionResponseByIssueGiver
      {
        get
        {
          return new TextObject("{=dE3vxfTo}Excellent.[if:convo_focused_happy] I'm sure they can learn a lot from your veterans.");
        }
      }

      public override TextObject IssueDiscussAlternativeSolution
      {
        get
        {
          return new TextObject("{=QRRgXOrN}As expected, your veterans have really sharpened up our boys. Please pass on my thanks to them, {?PLAYER.GENDER}madam{?}sir{\\?}.[if:convo_focused_happy][ib:hip]");
        }
      }

      public override bool IsThereAlternativeSolution => true;

      public override bool IsThereLordSolution => false;

      protected override TextObject AlternativeSolutionStartLog
      {
        get
        {
          TextObject to = new TextObject("{=Ci8NCwgW}{ISSUE_GIVER.LINK} a landowner in {SETTLEMENT}, asked you to train recruits for {?QUEST_GIVER.GENDER}her{?}him{\\?}. {?QUEST_GIVER.GENDER}She{?}He{\\?} gave you {NUMBER_OF_MEN} men, hoping to take them back when once they are veterans.{newline}You sent them with one of your companions {COMPANION.LINK} to hunt down some easy targets. You arranged to meet them in {RETURN_DAYS} days.");
          to.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject);
          to.SetCharacterProperties("COMPANION", this.AlternativeSolutionHero.CharacterObject);
          to.SetTextVariable("SETTLEMENT", this.IssueOwner.CurrentSettlement.EncyclopediaLinkWithName);
          to.SetTextVariable("RETURN_DAYS", this.GetTotalAlternativeSolutionDurationInDays());
          to.SetTextVariable("NUMBER_OF_MEN", this.GetTotalAlternativeSolutionNeededMenCount());
          return to;
        }
      }

      public override TextObject IssueAlternativeSolutionSuccessLog
      {
        get
        {
          TextObject to = new TextObject("{=AndfZYIJ}Your companion managed to return all of the troops {ISSUE_GIVER.LINK} gave you to train. {?ISSUE_GIVER.GENDER}She{?}He{\\?} sends you the following letter.\n\n“{?PLAYER.GENDER}Madam{?}Sir{\\?}, Thank you for looking after my men. You honored our agreement, and you have my gratitude. Please accept this {GOLD}{GOLD_ICON}.");
          to.SetCharacterProperties("ISSUE_GIVER", this.IssueOwner.CharacterObject);
          to.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter);
          to.SetTextVariable("GOLD", this.RewardGold);
          to.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return to;
        }
      }

      public LandlordTrainingForRetainersIssue(Hero issueOwner)
        : base(issueOwner, CampaignTime.DaysFromNow(30f))
      {
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        return issueEffect == DefaultIssueEffects.SettlementSecurity ? -1f : 0.0f;
      }

      public override (SkillObject, int) GetAlternativeSolutionSkill(Hero hero)
      {
        return (hero.GetSkillValue(DefaultSkills.Steward) >= hero.GetSkillValue(DefaultSkills.Leadership) ? DefaultSkills.Steward : DefaultSkills.Leadership, 120);
      }

      public override bool AlternativeSolutionCondition(out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(MobileParty.MainParty.MemberRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      protected override void AlternativeSolutionEndWithSuccessConsequence()
      {
        this.RelationshipChangeWithIssueOwner = 5;
        this.IssueOwner.AddPower(10f);
      }

      protected override void AlternativeSolutionEndWithFailureConsequence()
      {
        this.RelationshipChangeWithIssueOwner = -5;
        this.IssueOwner.AddPower(-10f);
      }

      public override bool DoTroopsSatisfyAlternativeSolution(
        TroopRoster troopRoster,
        out TextObject explanation)
      {
        explanation = TextObject.Empty;
        return QuestHelper.CheckRosterForAlternativeSolution(troopRoster, this.GetTotalAlternativeSolutionNeededMenCount(), ref explanation, 2);
      }

      public override bool IsTroopTypeNeededByAlternativeSolution(CharacterObject character)
      {
        return character.Tier >= 2;
      }

      public override IssueBase.IssueFrequency GetFrequency()
      {
        return IssueBase.IssueFrequency.VeryCommon;
      }

      public override bool IssueStayAliveConditions()
      {
        return !this.IssueOwner.CurrentSettlement.IsRaided && !this.IssueOwner.CurrentSettlement.IsUnderRaid;
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(60f), this.IssueDifficultyMultiplier, this.RewardGold);
      }

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flag,
        out Hero relationHero,
        out SkillObject skill)
      {
        skill = (SkillObject) null;
        relationHero = (Hero) null;
        flag = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flag |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (FactionManager.IsAtWarAgainstFaction(issueGiver.CurrentSettlement.MapFaction, Hero.MainHero.MapFaction))
          flag |= IssueBase.PreconditionFlags.AtWar;
        if (MobileParty.MainParty.MemberRoster.TotalManCount + this.BorrowedTroopCount > PartyBase.MainParty.PartySizeLimit)
          flag |= IssueBase.PreconditionFlags.PartySizeLimit;
        return flag == IssueBase.PreconditionFlags.None;
      }

      private int GetTier2TroopCount(TroopRoster troopRoster)
      {
        int tier2TroopCount = 0;
        foreach (TroopRosterElement troopRosterElement in (List<TroopRosterElement>) troopRoster.GetTroopRoster())
        {
          if (troopRosterElement.Character.Tier >= 2 && !troopRosterElement.Character.IsNotTransferableInPartyScreen)
            tier2TroopCount += troopRoster.GetTroopCount(troopRosterElement.Character);
        }
        return tier2TroopCount;
      }
    }

    public class LandlordTrainingForRetainersIssueQuest : QuestBase
    {
      private bool _popUpOpened;
      private CharacterObject _questGivenChar;
      private CharacterObject _questTargetChar;
      [SaveableField(1)]
      private readonly float _difficultyMultiplier;
      private CampaignTimeControlMode _campaignTimeControlModeCacheForDecisionPopUp;
      [SaveableField(2)]
      private JournalLog _playerStartsQuestLog;

      internal static void AutoGeneratedStaticCollectObjectsLandlordTrainingForRetainersIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._playerStartsQuestLog);
      }

      internal static object AutoGeneratedGetMemberValue_difficultyMultiplier(object o)
      {
        return (object) ((LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssueQuest) o)._difficultyMultiplier;
      }

      internal static object AutoGeneratedGetMemberValue_playerStartsQuestLog(object o)
      {
        return (object) ((LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssueQuest) o)._playerStartsQuestLog;
      }

      private int _borrowedTroopCount => 3 + MathF.Ceiling(17f * this._difficultyMultiplier);

      private TextObject _questStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=fcRLq8LL}{QUEST_GIVER.LINK}, a landowner in {QUEST_SETTLEMENT}, asked you to train some recruits for {?QUEST_GIVER.GENDER}her{?}him{\\?}. {?QUEST_GIVER.GENDER}She{?}He{\\?} gave you {NUMBER_OF_MEN} men, hoping to take them back when once they have some experience.\nThe easiest way to train them without putting them in too much danger is to attack weak parties.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("QUEST_SETTLEMENT", this.QuestGiver.CurrentSettlement.Name);
          parent.SetTextVariable("NUMBER_OF_MEN", this._borrowedTroopCount);
          return parent;
        }
      }

      private TextObject _totalSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=4RNREbPW}You managed to return all of the troops {QUEST_GIVER.LINK} gave you to train. {?QUEST_GIVER.GENDER}She{?}He{\\?} sends you the following letter.{newline}“{?PLAYER.GENDER}Madam{?}Sir{\\?}, Thank you for looking after my men. You honored our agreement, and you have my gratitude. Please accept this {GOLD}{GOLD_ICON}.”");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("GOLD", this.RewardGold);
          parent.SetTextVariable("GOLD_ICON", "{=!}<img src=\"General\\Icons\\Coin@2x\" extend=\"8\">");
          return parent;
        }
      }

      private TextObject _partialSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=yjAHh66a}You managed to return more than half of the troops {QUEST_GIVER.LINK} gave you to train. {?QUEST_GIVER.GENDER}She{?}He{\\?} sends you the following letter. {newline}“{?PLAYER.GENDER}Madam{?}Sir{\\?}, Thank you for returning my men to me. The losses they suffered are somewhat higher than I thought. I can only hope you did what you could to honor our agreement and try to keep them alive.”");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _weakSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=NXs7kr2B}You managed to return a fraction of the troops {QUEST_GIVER.LINK} gave you to train. {?QUEST_GIVER.GENDER}She{?}He{\\?} sends you the following letter. {newline}“{?PLAYER.GENDER}Madam{?}Sir{\\?}, Thank you for returning my men to me. The losses they suffered are somewhat higher than I thought. I can only hope you did what you could do to honor our agreement and try to keep them alive.”");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _failLog
      {
        get
        {
          TextObject parent = new TextObject("{=YBEB7GLa}All the borrowed troops in your party are gone. You are unable to return any of the troops {QUEST_GIVER.LINK} gave you to train. {?QUEST_GIVER.GENDER}She{?}He{\\?} sends you the following letter. {newline}“{?PLAYER.GENDER}Madam{?}Sir{\\?}, I understand that all my men are dead. I asked you to try and keep them alive. I do not know what to say to their kinfolk. This is a breach of my trust.”");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _epicFailLog
      {
        get
        {
          TextObject parent = new TextObject("{=eSpRuda1}You have decided to keep the borrowed troops {QUEST_GIVER.LINK} gave you to train. When {?QUEST_GIVER.GENDER}She{?}He{\\?} hears about this {?QUEST_GIVER.GENDER}she{?}he{\\?} sends you the following letter. {newline}“{?PLAYER.GENDER}Madam{?}Sir{\\?}, I made it clear that I expected my men to be returned to me. I consider this a betrayal of my trust.”");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _cancelLogOnWarDeclared
      {
        get
        {
          TextObject parent = new TextObject("{=TrewB5c7}Now your {?IS_MAP_FACTION}clan{?}kingdom{\\?} is at war with the {QUEST_GIVER.LINK}'s lord. Your agreement with {QUEST_GIVER.LINK} becomes invalid.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("IS_MAP_FACTION", Clan.PlayerClan.IsMapFaction ? 1 : 0);
          return parent;
        }
      }

      private TextObject _playerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _timeoutLog
      {
        get
        {
          TextObject parent = new TextObject("{=txtsL6QQ}You failed to train the troops by the time {QUEST_GIVER.LINK} needed them back. {?QUEST_GIVER.GENDER}She{?}He{\\?} sends you the following letter. “{?PLAYER.GENDER}Madam{?}Sir{\\?}, I expected my men to be returned to me. I consider this a breach of our agreement.”");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject _crimeLog
      {
        get
        {
          TextObject to = new TextObject("{=faZuFQUF}You are accused in {SETTLEMENT} of a crime, and {QUEST_GIVER.LINK} no longer wants your help.");
          to.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject);
          to.SetTextVariable("SETTLEMENT", this.QuestGiver.CurrentSettlement.Name);
          return to;
        }
      }

      public override TextObject Title
      {
        get
        {
          TextObject to = new TextObject("{=q2aed7tv}Train troops for {ISSUE_OWNER.NAME}");
          to.SetCharacterProperties("ISSUE_OWNER", this.QuestGiver.CharacterObject);
          return to;
        }
      }

      public override bool IsRemainingTimeHidden => false;

      public LandlordTrainingForRetainersIssueQuest(
        string questId,
        Hero giverHero,
        CampaignTime duration,
        float difficultyMultiplier,
        int rewardGold)
        : base(questId, giverHero, duration, rewardGold)
      {
        this._difficultyMultiplier = difficultyMultiplier;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad()
      {
        this._questGivenChar = MBObjectManager.Instance.GetObject<CharacterObject>("borrowed_troop");
        this._questGivenChar.SetTransferableInPartyScreen(false);
        this._questTargetChar = MBObjectManager.Instance.GetObject<CharacterObject>("veteran_borrowed_troop");
        this._questTargetChar.SetTransferableInPartyScreen(false);
        if (this._playerStartsQuestLog == null)
        {
          this._playerStartsQuestLog = this.JournalEntries.First<JournalLog>();
          this.UpdateQuestTaskStage(this._playerStartsQuestLog, PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar));
        }
        this.SetDialogs();
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.OnTroopsDesertedEvent.AddNonSerializedListener((object) this, new Action<MobileParty, TroopRoster>(this.OnTroopsDeserted));
        CampaignEvents.OnPlayerBattleEndEvent.AddNonSerializedListener((object) this, new Action<MapEvent>(this.OnPlayerBattleEnd));
        CampaignEvents.PlayerUpgradedTroopsEvent.AddNonSerializedListener((object) this, new Action<CharacterObject, CharacterObject, int>(this.OnPlayerUpgradedTroops));
        CampaignEvents.OnSettlementLeftEvent.AddNonSerializedListener((object) this, new Action<MobileParty, Settlement>(this.OnSettlementLeft));
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
        CampaignEvents.OnTroopGivenToSettlementEvent.AddNonSerializedListener((object) this, new Action<Hero, Settlement, TroopRoster>(this.OnTroopGivenToSettlement));
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=J8qFgwal}Excellent. I'll tell the lads to join your party.[if:convo_relaxed_happy][ib:confident2]")).Condition((ConversationSentence.OnConditionDelegate) (() => CharacterObject.OneToOneConversationCharacter == this.QuestGiver.CharacterObject)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).NpcLineWithVariation("{=7lee0h29}One thing - if one or two die, that's the fortunes of war, things could go even worse if we get raided and have no one who can fight back... But try not to get them all massacred. These men will take some risks for me, but not have their lives thrown away to no purpose.[if:convo_stern]").Variation("{=EaPQ2mm7}One thing - if possible, try not to get them all killed, will you? Green troops aren't much use to me, but corpses are even less.[if:convo_stern]", (object) "UngratefulTag", (object) 1, (object) "MercyTag", (object) -1).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=r9F1W4KZ}Yes? Have you been able to train my men?[if:convo_astonished]")).Condition((ConversationSentence.OnConditionDelegate) (() => CharacterObject.OneToOneConversationCharacter == this.QuestGiver.CharacterObject)).BeginPlayerOptions().PlayerOption(new TextObject("{=PVO3YFSq}Yes we are heading out now.")).NpcLine(new TextObject("{=weW40mKG}Good to hear that! Safe journeys.[if:convo_relaxed_happy]")).CloseDialog().PlayerOption(new TextObject("{=wErSpkjy}I'm still working on it.")).NpcLine(new TextObject("{=weW40mKG}Good to hear that! Safe journeys.[if:convo_relaxed_happy]")).CloseDialog().EndPlayerOptions().CloseDialog();
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this._questGivenChar = MBObjectManager.Instance.GetObject<CharacterObject>("borrowed_troop");
        this._questGivenChar.SetTransferableInPartyScreen(false);
        this._questTargetChar = MBObjectManager.Instance.GetObject<CharacterObject>("veteran_borrowed_troop");
        this._questTargetChar.SetTransferableInPartyScreen(false);
        PartyBase.MainParty.AddElementToMemberRoster(this._questGivenChar, this._borrowedTroopCount);
        PartyBase.MainParty.ItemRoster.AddToCounts(DefaultItems.Grain, 3);
        this._playerStartsQuestLog = this.AddDiscreteLog(this._questStartLog, new TextObject("{=wUb5h4a3}Trained Troops"), PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar), this._borrowedTroopCount);
      }

      private void OnPlayerBattleEnd(MapEvent mapEvent)
      {
        if (!mapEvent.IsPlayerMapEvent)
          return;
        this.CheckFail();
      }

      private void OnTroopsDeserted(MobileParty mobileParty, TroopRoster desertedTroops)
      {
        if (!mobileParty.IsMainParty)
          return;
        this.CheckFail();
      }

      private void OnPlayerUpgradedTroops(
        CharacterObject upgradeFromTroop,
        CharacterObject upgradeToTroop,
        int number)
      {
        if (upgradeFromTroop == this._questGivenChar && upgradeToTroop == this._questTargetChar && number > 0)
          this.UpdateQuestTaskStage(this._playerStartsQuestLog, PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar));
        if (this.CheckFail())
          return;
        this.CheckSuccess();
      }

      private void OnSettlementLeft(MobileParty party, Settlement settlement)
      {
        if (this.CheckFail())
          return;
        this.CheckSuccess();
      }

      protected override void HourlyTick()
      {
        if (!this.IsOngoing || this.CheckFail())
          return;
        this.CheckSuccess();
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if (!mapEvent.IsForcingSupplies && !mapEvent.IsForcingVolunteers && !mapEvent.IsRaid || attackerParty != PartyBase.MainParty || !mapEvent.MapEventSettlement.IsVillage || mapEvent.MapEventSettlement != this.QuestGiver.CurrentSettlement)
          return;
        this.CriminalActionPerformedTowardsSettlement();
      }

      private void OnTroopGivenToSettlement(
        Hero giverHero,
        Settlement recipientSettlement,
        TroopRoster roster)
      {
        if (giverHero != Hero.MainHero || this.CheckFail())
          return;
        this.CheckSuccess();
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (!this.QuestGiver.CurrentSettlement.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        this.CompleteQuestWithCancel(this._cancelLogOnWarDeclared);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this._playerDeclaredWarQuestLogText, this._cancelLogOnWarDeclared);
      }

      private void RemoveBorrowedTroopsFromParty(PartyBase party)
      {
        int troopCount1 = party.MemberRoster.GetTroopCount(this._questTargetChar);
        if (troopCount1 > 0)
          party.MemberRoster.AddToCounts(this._questTargetChar, -troopCount1);
        int troopCount2 = party.MemberRoster.GetTroopCount(this._questGivenChar);
        if (troopCount2 <= 0)
          return;
        party.MemberRoster.AddToCounts(this._questGivenChar, -troopCount2);
      }

      private void TurnRemainingQuestTroopsIntoNormalTroops(PartyBase party)
      {
        int elementNumber1 = party.MemberRoster.GetElementNumber(this._questGivenChar);
        int elementNumber2 = party.MemberRoster.GetElementNumber(this._questTargetChar);
        int elementNumber3 = party.PrisonRoster.GetElementNumber(this._questGivenChar);
        int elementNumber4 = party.PrisonRoster.GetElementNumber(this._questTargetChar);
        if (elementNumber1 > 0)
        {
          party.MemberRoster.AddToCounts(this._questGivenChar, -elementNumber1);
          party.MemberRoster.AddToCounts(this.QuestGiver.Culture.BasicTroop, elementNumber1);
        }
        if (elementNumber2 > 0)
        {
          party.MemberRoster.AddToCounts(this._questTargetChar, -elementNumber2);
          party.MemberRoster.AddToCounts(this.QuestGiver.Culture.EliteBasicTroop, elementNumber2);
        }
        if (elementNumber3 > 0)
        {
          party.PrisonRoster.AddToCounts(this._questGivenChar, -elementNumber3);
          party.PrisonRoster.AddToCounts(this.QuestGiver.Culture.BasicTroop, elementNumber3);
        }
        if (elementNumber4 <= 0)
          return;
        party.PrisonRoster.AddToCounts(this._questTargetChar, -elementNumber4);
        party.PrisonRoster.AddToCounts(this.QuestGiver.Culture.EliteBasicTroop, elementNumber4);
      }

      private bool CheckFail()
      {
        if (PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar) != 0 || PartyBase.MainParty.MemberRoster.GetTroopCount(this._questGivenChar) != 0)
          return false;
        this.Fail();
        return true;
      }

      private void CheckSuccess(bool isConversationEnded = false)
      {
        if (PartyBase.MainParty.MemberRoster.GetTroopCount(this._questGivenChar) != 0 || PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar) <= 0 || this._popUpOpened || !(Campaign.Current.ConversationManager.OneToOneConversationHero == null | isConversationEnded))
          return;
        this.OpenDecisionPopUp();
      }

      private void OpenDecisionPopUp()
      {
        this._popUpOpened = true;
        this._campaignTimeControlModeCacheForDecisionPopUp = Campaign.Current.TimeControlMode;
        Campaign.Current.TimeControlMode = CampaignTimeControlMode.Stop;
        TextObject parent = new TextObject("{=LO7EjoY7}The borrowed troops remaining in your party are now all experienced. You can send them back to {QUEST_GIVER.LINK}.");
        StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
        InformationManager.ShowInquiry(new InquiryData("", parent.ToString(), true, true, new TextObject("{=ikDX1Fd7}Send the troops back").ToString(), new TextObject("{=yFahppU2}Hold on to them").ToString(), new Action(this.CompleteQuestSuccessfully), new Action(this.EpicFail)));
      }

      private void CompleteQuestSuccessfully()
      {
        Campaign.Current.TimeControlMode = this._campaignTimeControlModeCacheForDecisionPopUp;
        int troopCount = PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar);
        PartyBase.MainParty.MemberRoster.AddToCounts(this._questTargetChar, -troopCount);
        PartyBase.MainParty.MemberRoster.AddToCounts(this._questGivenChar, -PartyBase.MainParty.MemberRoster.GetTroopCount(this._questGivenChar));
        if (troopCount >= this._borrowedTroopCount)
          this.TotalSuccess();
        else if ((double) this._borrowedTroopCount * 0.5 < (double) troopCount && troopCount < this._borrowedTroopCount)
        {
          this.PartialSuccess();
        }
        else
        {
          if (0 >= troopCount || (double) troopCount > (double) this._borrowedTroopCount * 0.5)
            return;
          this.WeakSuccess();
        }
      }

      private void TotalSuccess()
      {
        Clan.PlayerClan.AddRenown(2f);
        this.RelationshipChangeWithQuestGiver = 5;
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 50)
        });
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        this.QuestGiver.AddPower(10f);
        this.AddLog(this._totalSuccessLog);
        this.CompleteQuestWithSuccess();
      }

      private void PartialSuccess()
      {
        Clan.PlayerClan.AddRenown(1f);
        this.RelationshipChangeWithQuestGiver = 3;
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 30)
        });
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        this.QuestGiver.AddPower(10f);
        this.AddLog(this._partialSuccessLog);
        this.CompleteQuestWithSuccess();
      }

      private void WeakSuccess()
      {
        Clan.PlayerClan.AddRenown(1f);
        this.RelationshipChangeWithQuestGiver = 1;
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, 10)
        });
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        this.QuestGiver.AddPower(10f);
        this.AddLog(this._weakSuccessLog);
        this.CompleteQuestWithSuccess();
      }

      private void Fail()
      {
        this.RelationshipChangeWithQuestGiver = -5;
        this.QuestGiver.AddPower(-10f);
        this.AddLog(this._failLog);
        this.CompleteQuestWithFail();
      }

      private void EpicFail()
      {
        Campaign.Current.TimeControlMode = this._campaignTimeControlModeCacheForDecisionPopUp;
        this.RelationshipChangeWithQuestGiver = -10;
        this.QuestGiver.AddPower(-10f);
        ChangeCrimeRatingAction.Apply(this.QuestGiver.MapFaction, 10f);
        TraitLevelingHelper.OnIssueSolvedThroughQuest(this.QuestGiver, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, -10)
        });
        this.AddLog(this._epicFailLog);
        this.CompleteQuestWithFail();
      }

      private void CriminalActionPerformedTowardsSettlement()
      {
        this.RelationshipChangeWithQuestGiver = -5;
        this.QuestGiver.AddPower(-10f);
        TraitLevelingHelper.OnIssueSolvedThroughQuest(Hero.MainHero, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, -50)
        });
        this.CompleteQuestWithFail(this._crimeLog);
      }

      protected override void OnFinalize()
      {
        this._questGivenChar = MBObjectManager.Instance.GetObject<CharacterObject>("borrowed_troop");
        this._questTargetChar = MBObjectManager.Instance.GetObject<CharacterObject>("veteran_borrowed_troop");
        foreach (MobileParty mobileParty in MobileParty.All.ToList<MobileParty>())
        {
          if (!mobileParty.IsMilitia)
            this.TurnRemainingQuestTroopsIntoNormalTroops(mobileParty.Party);
        }
      }

      protected override void OnBeforeTimedOut(
        ref bool completeWithSuccess,
        ref bool doNotResolveTheQuest)
      {
        if (PartyBase.MainParty.MemberRoster.GetTroopCount(this._questTargetChar) <= 0)
          return;
        doNotResolveTheQuest = true;
        if (this._popUpOpened || MobileParty.MainParty.MapEvent != null)
          return;
        this.OpenDecisionPopUp();
      }

      protected override void OnTimedOut()
      {
        this.RelationshipChangeWithQuestGiver = -5;
        this.QuestGiver.AddPower(-10f);
        this.RemoveBorrowedTroopsFromParty(PartyBase.MainParty);
        this.AddLog(this._timeoutLog);
      }
    }

    public class LandlordTrainingForRetainersIssueTypeDefiner : SaveableTypeDefiner
    {
      public LandlordTrainingForRetainersIssueTypeDefiner()
        : base(410000)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssue), 1);
        this.AddClassDefinition(typeof (LandlordTrainingForRetainersIssueBehavior.LandlordTrainingForRetainersIssueQuest), 2);
      }
    }
  }
}
